# 引入中间件的基础模块
from django.utils.deprecation import MiddlewareMixin
# 引入用户的类
from web.models import UserInfo


# 定义中间件的类
class AuthMiddleware(MiddlewareMixin):

    # 定义request的函数
    def process_request(self, request):
        """如果用户已登录，给request中加一个变量（存储当前用户）"""
        # 获取当前session中的id
        session_user_id = request.session.get('id')
        # 获取用户对象
        user_object = UserInfo.objects.filter(id=session_user_id).first()
        # 把当前用户添加到request
        request.tracer_user = user_object